/*
 * Copyright (C) 2009 Dimitrios C. Michalakos
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import com.cs.util.db.DatabaseEngineEnum;
import javax.servlet.ServletContext;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;

/**
 *
 * @author dimitris@jmike.gr
 */
public class Controller {

    private final UriInfo uriInfo;
    private final boolean isSecure;
    private final String appTitle;
    private final String authRealm;
    private final int httpsPort;
    private final Meta meta;

    public Controller(UriInfo uriInfo, SecurityContext securityContext, ServletContext servletContext) {
        this.uriInfo = uriInfo;
        this.isSecure = securityContext.isSecure();
        this.appTitle = servletContext.getInitParameter("app-title");
        this.authRealm = servletContext.getInitParameter("auth-realm");
        this.httpsPort = Integer.parseInt(servletContext.getInitParameter("https-port"));
        this.meta = new Meta(DatabaseEngineEnum.valueOf(servletContext.getInitParameter("db-type")),
                servletContext.getInitParameter("db-host"),
                Integer.parseInt(servletContext.getInitParameter("db-port")),
                servletContext.getInitParameter("db-schema"),
                servletContext.getInitParameter("db-username"),
                servletContext.getInitParameter("db-password"));
    }

//    /**
//     * Returns an Xhtml Table containing the databases listed under the specified account.
//     * This resource is secured via SSL and can only be displayed to users that belong to the specified account.
//     * @param authHeader the BASIC authentication HTTP header containing the current user's credentials.
//     * @param accountName the name of the user's parent account.
//     * @return
//     */
//    public Response db_1_0_databases_getXhtml(String authHeader, String accountName) {
////        if (isSecure) {//SSL enabled
//        final int accountId = meta.getAccountId(accountName);//get accountId
//        if (accountId > 0) {//account exists
//            if (meta.existsUser(authHeader, accountId)) {//user is authenticated
//                try {
//                    Database db = meta.getDatabase();//open the database
//                    /* design the sql */
//                    SQLDesigner designer = db.getSQLDesigner();
//                    MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();//get parameters
//                    designer.parse("database?accountid=" + String.valueOf(accountId), parameters);
//                    final String sql = designer.getSelectSQL();
//                    /* get the resultset */
//                    ResultSet rs = db.getResultSet(sql);
//                    /* get the representation */
//                    XhtmlTable representation = db.getXhtmlTable(rs);
//                    representation.setTitle("View databases of " + accountName + " - " + appTitle);
//                    representation.addAction("edit", "Edit", "./" + accountName + "/{name}.html");
//                    representation.addAction("viewTables", "View tables", "./" + accountName + "/{name}/tables.html");
//                    final String entity = representation.display();
//                    rs.close();//close the resultset
//                    db.close();//close the database
//                    return Response.status(200).entity(entity).build();
//                } catch (SQLException ex) {
//                    return Response.status(500).entity(ex.getMessage()).build();//"Internal Server Error"
//                } catch (InvalidCollectionException ex) {
//                    return Response.status(404).entity(ex.getMessage()).build();//"Not Found"
//                }
//            } else {//user is not authenticated
//                return Response.status(401).header("WWW-Authenticate", "Basic realm=\"" + authRealm + "\"").build();//"Unauthorized"
//            }
//        } else {//account does not exist in meta database
//            return Response.status(404).build();//"Not Found"
//        }
////        } else {//SSL not enabled
////            final URI location = uriInfo.getRequestUriBuilder().scheme("https").port(httpsPort).build();//Upgrade URI to https
////            return Response.status(301).header("Location", location).build();//"Moved Permanently"
////        }
//    }
//
//    /**
//     * Returns an Xhtml Form containing the designated database of the specified account.
//     * This resource is secured via SSL and can only be displayed to the users of the specified account.
//     * @param dbName the name of the database.
//     * @param authHeader the BASIC authentication HTTP header containing the current user's credentials.
//     * @param accountName the name of the user's parent account.
//     * @return
//     */
//    public Response db_1_0_database_getXhtml(String dbName, String authHeader, String accountName) {
////        if (isSecure) {//SSL enabled
//        final int accountId = meta.getAccountId(accountName);//get accountId
//        if (accountId > 0) {//account exists
//            if (meta.existsUser(authHeader, accountId)) {//user is authenticated
//                try {
//                    Database db = meta.getDatabase();//open the database
//                    /* design the sql */
//                    SQLDesigner designer = db.getSQLDesigner();
//                    MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();//get parameters
//                    designer.parse("database?accountid=" + String.valueOf(accountId) + "&name=" + dbName, parameters);
//                    final String sql = designer.getSelectSQL();
//                    /* get the resultset */
//                    ResultSet rs = db.getResultSet(sql);
//                    /* get the representation */
//                    XhtmlForm representation = db.getXhtmlForm(rs);
//                    representation.setTitle("Edit " + dbName + "@" + accountName + " database - " + appTitle);
//                    representation.setFormAction(uriInfo.getRequestUri().toString());
//                    final String entity = representation.display();
//                    rs.close();//close the resultset
//                    db.close();//close the database
//                    return Response.status(200).entity(entity).build();
//                } catch (SQLException ex) {
//                    return Response.status(500).entity(ex.getMessage()).build();//"Internal Server Error"
//                } catch (InvalidCollectionException ex) {
//                    return Response.status(404).entity(ex.getMessage()).build();//"Not Found"
//                }
//            } else {//user is not authenticated
//                return Response.status(401).header("WWW-Authenticate", "Basic realm=\"" + authRealm + "\"").build();//"Unauthorized"
//            }
//        } else {//account does not exist in meta database
//            return Response.status(404).build();//"Not Found"
//        }
////        } else {//SSL not enabled
////            final URI location = uriInfo.getRequestUriBuilder().scheme("https").port(httpsPort).build();//Upgrade URI to https
////            return Response.status(301).header("Location", location).build();//"Moved Permanently"
////        }
//    }
//
//    /**
//     * Updates the designated database under the specified account.
//     * This resource is secured via SSL and can only be displayed to the users of the specified account.
//     * @param dbName the name of the database.
//     * @param authHeader the BASIC authentication HTTP header containing the current user's credentials.
//     * @param accountName the name of the user's parent account.
//     * @param form the form data encoded as multipart/form-data.
//     * @return
//     * @throws javax.mail.MessagingException
//     */
////    public Response db_1_0_database_putFormMultipart(String dbName, String authHeader, String accountName, MimeMultipart form) throws MessagingException {
//////        if (isSecure) {//SSL enabled
////        final int accountId = meta.getAccountId(accountName);//get accountId
////        if (accountId > 0) {//account exists
////            if (meta.existsUser(authHeader, accountId)) {//user is authenticated
////                try {
////                    Database db = meta.getDatabase();//open the database
////                    /* get the resultset */
////                    MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters();//get parameters
////                    ResultSet rs = db.getResultSet("database?accountid=" + String.valueOf(accountId), parameters);
////                    /* get the representation */
////                    XhtmlForm representation = db.getXhtmlForm(rs);
////                    representation.setTitle("Edit " + dbName + "@" + accountName + " database - " + appTitle);
////                    representation.setFormAction(uriInfo.getRequestUri().toString());
////                    final String entity = representation.display();
////                    rs.close();//close the resultset
////                    db.close();//close the database
////                    return Response.status(200).entity(entity).build();
////                } catch (SQLException ex) {
////                    return Response.status(500).entity(ex.getMessage()).build();//"Internal Server Error"
////                } catch (InvalidCollectionException ex) {
////                    return Response.status(404).entity(ex.getMessage()).build();//"Not Found"
////                }
////            } else {//user is not authenticated
////                return Response.status(401).header("WWW-Authenticate", "Basic realm=\"" + authRealm + "\"").build();//"Unauthorized"
////            }
////        } else {//account does not exist in meta database
////            return Response.status(404).build();//"Not Found"
////        }
//////        } else {//SSL not enabled
//////            final URI location = uriInfo.getRequestUriBuilder().scheme("https").port(httpsPort).build();//Upgrade URI to https
//////            return Response.status(301).header("Location", location).build();//"Moved Permanently"
//////        }
////    }
//
//    /**
//     * Inserts a new database under the specified account.
//     * This resource is secured via SSL and can only be displayed to the users of the specified account.
//     * @param authHeader the BASIC authentication HTTP header containing the current user's credentials.
//     * @param accountName the name of the user's parent account.
//     * @param form the form data encoded as multipart/form-data.
//     * @return
//     * @throws javax.mail.MessagingException
//     */
//    public Response db_1_0_database_postFormMultipart(String authHeader, String accountName, MimeMultipart form) throws MessagingException {
////        if (isSecure) {//SSL enabled
//        final int accountId = meta.getAccountId(accountName);//get accountId
//        if (accountId > 0) {//account exists
//            if (meta.existsUser(authHeader, accountId)) {//user is authenticated
//                try {
//                    Database db = meta.getDatabase();//open the database
//                    /* design the sql */
//                    SQLDesigner designer = db.getSQLDesigner();
//                    designer.parse("database?accountid=" + String.valueOf(accountId), form);
//                    final String sql = designer.getInsertSQL();
//                    /* execute the sql */
//
//                    /* get the representation */
//                    return Response.status(200).entity(sql).build();
//                } catch (SQLException ex) {
//                    return Response.status(500).entity(ex.getMessage()).build();//"Internal Server Error"
//                } catch (InvalidCollectionException ex) {
//                    return Response.status(404).entity(ex.getMessage()).build();//"Not Found"
//                }
//            } else {//user is not authenticated
//                return Response.status(401).header("WWW-Authenticate", "Basic realm=\"" + authRealm + "\"").build();//"Unauthorized"
//            }
//        } else {//account does not exist in meta database
//            return Response.status(404).build();//"Not Found"
//        }
////        } else {//SSL not enabled
////            final URI location = uriInfo.getRequestUriBuilder().scheme("https").port(httpsPort).build();//Upgrade URI to https
////            return Response.status(301).header("Location", location).build();//"Moved Permanently"
////        }
//    }
}
